package chloroform

import javax.servlet.http.{HttpServletResponse, HttpServletRequest}
import util.JsonRendererUtil
import argo.jdom.{JsonNodeBuilder, JsonRootNode}

/**
 * User: zslajchrt
 * Date: 7.3.11
 * Time: 19:49
 */

trait MessageHandlerFactory {

  type MessageHandlerType <: MessageHandler

  abstract class MessageTypeEnum extends Enumeration {
    type MessageType
  }

  val getHandledMessageIds: MessageTypeEnum

  def getHandler(messageType: getHandledMessageIds.Value, message: JsonRootNode, req: HttpServletRequest): MessageHandlerType

  def returnHandler(handler: MessageHandlerType, req: HttpServletRequest)
}

trait MessageHandler {
  def handleMessage(message: JsonRootNode): MessageOutcome
}

trait HttpRenderer {
  def render(request: HttpServletRequest, response: HttpServletResponse)
}

sealed abstract case class MessageOutcome
case class ResponseRenderer(renderer: HttpRenderer) extends MessageOutcome
case class Forwarder(target: String) extends MessageOutcome

object JsonResponse {
  def apply(outputMessageBuilder: JsonNodeBuilder[JsonRootNode]) = {
    ResponseRenderer(new HttpRenderer {
      def render(request: HttpServletRequest, response: HttpServletResponse) {
        val jsonRenderer = JsonRendererUtil.makeRenderer(outputMessageBuilder)
        jsonRenderer.render(response.getWriter)
      }
    })
  }
}

